package cn.nn200433.mqtt.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.nn200433.mqtt.service.IMqttConnectService;
import cn.nn200433.mqtt.service.IMqttHandlerService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * mqtt处理程序上下文
 *
 * @author nn200433
 * @date 2022-06-28 028 10:31:57
 */
@Slf4j
public class MqttHandlerContext {
    
    /** 连接服务 */
    private final IMqttConnectService              connectService;
    /** 上下文映射 */
    private final Map<String, IMqttHandlerService> contextMap;
    
    public MqttHandlerContext(IMqttConnectService cService, List<IMqttHandlerService> handleList) {
        connectService = cService;
        contextMap     = CollUtil.defaultIfEmpty(handleList, ListUtil.empty()).stream()
                .filter(s -> StrUtil.isNotBlank(s.getSubscribeTopic()))
                .collect(Collectors.toMap(IMqttHandlerService::getSubscribeTopic, Function.identity()));
        log.info("---> 【MQTT】已装载消息策略：{}", contextMap.keySet());
    }
    
    /**
     * 获取连接服务
     *
     * @return {@link IMqttConnectService }
     * @author nn200433
     */
    public IMqttConnectService getConnectService() {
        return connectService;
    }
    
    /**
     * 获取处理程序策略
     *
     * @param subscribeTopic 订阅主题
     * @return {@link IMqttHandlerService }
     * @author nn200433
     */
    public IMqttHandlerService getHandlerStrategy(String subscribeTopic) {
        return contextMap.get(subscribeTopic);
    }
    
}
